<template>
  <div v-if="isAuth(['ROOT', 'DRIVER:SELECT'])">
    <!--查询栏-->
    <el-form :inline="true" :model="searchForm" :rules="dataRule" ref="searchForm">
      <el-form-item prop="name">
        <el-input v-model="searchForm.query.name" placeholder="司机姓名" size="medium" class="input"
                  clearable="clearable"/>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.query.contractStatus" class="input" placeholder="合同状态" size="medium"
                   clearable="clearable">
          <el-option label="有效" value="0"/>
          <el-option label="作废" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" @click="loadDataList()">查询合同</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" @click="uploadForm()">上传合同</el-button>
      </el-form-item>
    </el-form>

    <!--主页面表格-->
    <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        cell-style="padding: 2px 0"
        style="width: 100%;"
        size="medium"
        :row-key="getRowKeys"
    >
      <el-table-column prop="name" header-align="center" align="center" min-width="80" label="司机姓名"/>
      <el-table-column prop="number" header-align="center" align="center" min-width="110" label="合同编号"/>
      <el-table-column prop="contractStatus" header-align="center" align="center" min-width="100" label="合同状态">
        <template #default="scope">
          <el-tag v-if="scope.row.contractStatus === 0" type="success">有效</el-tag>
          <el-tag v-if="scope.row.contractStatus === 1" type="danger">作废</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="uploadName" header-align="center" align="center" min-width="180" label="上传人"/>
      <el-table-column header-align="center" align="center" width="250" label="操作">
        <template #default="scope">
          <el-button type="text" size="medium" v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                     @click="showContractModel(scope.row)">
            查看合同
          </el-button>
          <el-button type="text" size="medium" v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                     @click="cancelContract(scope.row.id)" :disabled="scope.row.contractStatus === 1">
            作废
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="searchForm.page"
        :page-sizes="[10, 20, 50]"
        :page-size="searchForm.rows"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!--上传文档-->
    <el-dialog v-model="upload.uploadContractModelVisible" title="上传文档" width="400px" center>
      <div class="notice">上传合同</div>
      <el-form-item>
        <!-- 选择司机下拉框 -->
        <div style="display: flex; align-items: center; margin-top: 10px;">
          <span style="width: 60px; text-align: right; margin-right: 10px;">选择司机:</span>
          <el-select
              v-model=upload.driverId
              placeholder="选择司机"
              clearable
              style="flex: 1;"
              @change="handleDriverChange"
          >
            <el-option
                v-for="driver in upload.driverList"
                :key="driver.id"
                :label="driver.name"
                :value="driver.id"
            />
          </el-select>
        </div>
        <!-- 合同编号输入框 -->
        <div style="display: flex; align-items: center; margin-top: 10px;">
          <span style="width: 60px; text-align: right; margin-right: 10px;">合同编号:</span>
          <el-input type="text" v-model="upload.contractNumber" placeholder="填写合同编号" style="flex: 1;"/>
        </div>
        <!-- 上传文件按钮 -->
        <div style="display: flex; align-items: center; margin-top: 20px;">
          <span style="width: 100px; text-align: right; margin-right: 10px;"></span>
          <el-upload
              v-model:file-list="upload.fileList"
              :file-list="upload.fileList"
              :on-change="handleChange"
              :on-remove="handleRemove"
              accept=".pdf"
              :limit="1"
              :auto-upload="false"
              style="flex: 1;">
            <el-button type="primary" style="width: 100%;">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件格式: pdf</div>
          </el-upload>
        </div>
      </el-form-item>
      <template #footer>
				<span class="dialog-footer">
          <el-button type="primary" @click="uploadContractModel(false)">取消</el-button>
					<el-button type="danger" @click="uploadContract()">确定</el-button>
				</span>
      </template>
    </el-dialog>

    <!--预览文档-->
    <el-dialog v-model="view.contractModelVisible" @open="loadPdf" title="PDF预览" width="600px" center>
      <div id="pdf-viewer" style="width: 100%; height: 500px;"></div>
    </el-dialog>

    <update ref="update" @refreshDataList="loadDataList"></update>
  </div>
</template>
<script>
import Update from './driver-update.vue';
import PDFObject from 'pdfobject';

export default {
  components: {
    Update
  },
  data() {
    return {
      //分页查询相关数据
      searchForm: {
        query: {
          name: null,
          number: null,
          contractStatus: null,
          uploadName: null,
        },
        page: 1,
        rows: 10
      },
      dataList: [],
      totalCount: 0,
      dataListLoading: false,
      //行键
      getRowKeys(row) {
        return row.id;
      },
      //数据规则
      dataRule: {
        name: [{required: false, pattern: '^[\u4e00-\u9fa5]{1,10}$', message: '姓名格式错误'}],
        //@TODO 合同编号规则
        number: [{
          required: false,
          pattern: '^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$',
          message: '身份证格式错误'
        }]
      },
      //上传文件相关数据
      upload: {
        //是否显示上传文件模态框
        uploadContractModelVisible: false,
        //上传页面司机数据
        driverList: [],
        //上传文件编号
        contractNumber: null,
        //上传的文件列表
        fileList: [],
        //返回给后端的值
        driverId: null,
        driverName: null,
      },
      //查看合同相关数据
      view: {
        //是否显示上传文件模态框
        contractModelVisible: false,
        //pdf文件路径
        pdfSrc: null,
      },
    };
  },
  methods: {
    //1.上传合同单机事件相关方法
    //1.1 上传合同单机事件
    uploadForm() {
      this.uploadContractModel(true);
      this.loadDriverList();
    },
    //1.2 合同上传弹窗
    uploadContractModel(visible) {
      this.upload.uploadContractModelVisible = visible;
    },
    //1.3 查询未签合同的司机
    loadDriverList() {
      let _this = this;
      _this.get("/driver/manager/driver/unsignedContractList", _this.searchForm, (res) => {
        let {success, message, data} = res;
        if (success) {
          _this.upload.driverList = data;
        } else {
          this.$message({message: message, type: 'error', duration: 1200})
        }
      });
    },

    //2.上传合同表单相关方法
    //2.1 选择司机
    handleDriverChange(id) {
      const selectedDriver = this.upload.driverList.find(driver => driver.id === id);
      if (selectedDriver) {
        this.upload.driverName = selectedDriver.name;
      } else {
        this.upload.driverName = null;
      }
    },
    //2.2 上传文件变化的钩子方法
    handleChange(file, fileList) {
      this.fileTypeCheck(file, fileList);
    },
    //2.3 文件类型检查
    fileTypeCheck(file, fileList) {
      const isPDF = file.name.toLowerCase().endsWith('.pdf');
      if (!isPDF) {
        this.$message.error('只能上传 PDF 格式的文件!');
        // 从 fileList 中移除不合格的文件
        const index = fileList.indexOf(file);
        if (index !== -1) {
          // 删除不合格文件
          fileList.splice(index, 1);
        }
      }
      // 更新到外部的 fileList
      this.upload.fileList = fileList;
    },
    //2.4 上传文件删除的钩子方法
    handleRemove(file, fileList) {
      this.upload.fileList = fileList;
    },
    //2.5 上传合同
    uploadContract() {
      let _this = this;
      let formData = new FormData();
      //上传的文件
      formData.append('file', _this.upload.fileList[0].raw);
      //保证其余数据
      let jsonData = {
        //司机id
        driverId: this.upload.driverId,
        //司机姓名
        driverName: this.upload.driverName,
        //合同编号
        number: this.upload.contractNumber,
      };
      //转化为二进制文件
      const blob = new Blob([JSON.stringify(jsonData)], {
        type: 'application/json',
      });
      formData.append('data', blob);
      //添加请求头表明这是一个form-data文件
      const headers = {
        'Content-Type': 'multipart/form-data'
      };
      //上传文件
      _this.post("/driver/manager/driverContract/upload", formData, (res) => {
        let {success, message} = res;
        if (success) {
          _this.loadDataList();
          _this.$message({message: '合同上传成功', type: 'success', duration: 1200});
          _this.upload.uploadContractModelVisible = false;
        } else {
          this.$message({message: message, type: 'error', duration: 1200});
        }
      }, headers);
    },

    //3.合同预览相关方法
    //3.1 合同预览弹窗
    showContractModel(row) {
      //腾讯cos的文件需要加上该后缀用于预览
      this.view.pdfSrc = row.filePath + "?ci-process=doc-preview&dstType=html";
      this.view.contractModelVisible = true;
    },
    /**
     * 3.2加载pdf-使用 PDFObject.embed() 方法将 PDF 文件嵌入到指定的 DOM 元素中
     * 注意这里都是异步操作 , 需要等到 el-dialog 的窗口完全加载完成之后才能加载 pdf 进去
     * 在 el-dialog 中加入 @open="loadPdf" 保证加载完成后调用该方法
     */
    loadPdf() {
      PDFObject.embed(this.view.pdfSrc, "#pdf-viewer");
    },

    //4.合同作废
    cancelContract(contractId) {
      this.$confirm("确定要作废该合同？").then(() => {
        this.get("/driver/manager/driverContract/cancel/" + contractId, (res) => {
          let {success, message, result} = res;
          if (success) {
            this.$message({message: '作废成功', type: 'success', duration: 1200});
            this.loadDataList();
          } else {
            this.$message({message: message, type: 'error', duration: 1200});
          }
        });
      });
    },

    //5. 加载列表数据
    loadDataList() {
      let _this = this;
      for (var prop in _this.searchForm.query) {
        if (_this.searchForm.query[prop] === "") {
          _this.searchForm.query[prop] = null;
        }
      }
      _this.post("/driver/manager/driverContract/pagelist", _this.searchForm, (res) => {
        let {success, data} = res;
        if (success) {
          _this.totalCount = data.total;
          _this.dataList = data.rows;
        }
      });
    }
  },
  created: function () {
    this.loadDataList();
  }
}
;
</script>
<style lang="less" scoped="scoped">
@import url('driver.less');
</style>
